<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h2>With <code>"express"</code> npm package</h2>
  <form class="form">
    <div>Text field title: <input type="text" name="title" /></div>
    <div>File: <input type="file" name="avatar" multiple="multiple" /></div>
    <input type="submit" value="Upload" />
  </form>

  <script>
    const $ = s => document.querySelector(s)

    $('.form').addEventListener('submit', e => {
      e.preventDefault()

      // 利用 FormData 构建 ajax 提交的数据
      const data = new FormData(e.target)
      
      // 利用 ajax 提交表单数据
      // 实现文件上传

      // XMLHttpRequest
      const xhr = new XMLHttpRequest()
      // 连接
      xhr.open('POST', 'http://localhost:9527/api/v1/files', true)
      // 设置请求头
      // xhr.setRequestHeader('Content-Type', 'multipart/form-data')
      xhr.setRequestHeader('token', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InhpYW9ob25nIiwibmFtZSI6IuWwj-e6oiJ9.zd9QpbJqrjqxHDZa-UsImX2W5qVa6hyOrEg7kLnrgw4')
      // 发送请求
      xhr.send(data)
      // 处理响应
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            const data = JSON.parse(xhr.responseText)
            console.log('成功：', data)
          } else {
            console.error('失败')
          }
        }
      }
    }, false)
  </script>
</body>
</html>